package com.site.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.site.dto.master.PropertyBizBean;
import com.site.service.master.PropertyService;
import com.site.util.constant.Constants;


public class PropertyUtil {

	private ApplicationContext springCtx = null;
	private PropertyService propertyService = null;
	
	/**
	 * 获得所有属性数据
	 * @param context
	 * @return
	 */
	public Map<String,String> getAllProperty(ServletContext context) {
		if(propertyService==null) {
			springCtx=WebApplicationContextUtils.getWebApplicationContext(context);
			propertyService=(PropertyService)springCtx.getBean("propertyService");
		}
		List<PropertyBizBean> propertyList = propertyService.getAllProperty();
		Map<String,String> map = new HashMap<String,String>();
		if(null == propertyList || propertyList.isEmpty()){
			return null;
		}
		if(propertyList.size()>0){
			for(PropertyBizBean property:propertyList)
			{
				map.put(property.getPropertyKey(), property.getPropertyValue());
			}
		}
		return map;
	}
	
	/**
	 * 根据键值获取属性值
	 * @param key
	 * @param request
	 * @return
	 */
	public static String getPropertyValueByKey(String key,HttpServletRequest request)
	{
		Map<String,String> map =(Map<String,String>)request.getSession().getServletContext().getAttribute(Constants.PROPERTY_NAME);
		if(map!=null&&map.size()>0)
			return map.get(key);
		return null;
	}
	/**
	 * 根据键值获取属性值
	 * @param key
	 * @param request
	 * @return
	 */
	public static String getPropertyValueByKey(String key,ServletContext context)
	{
		Map<String,String> map =(Map<String,String>)context.getAttribute(Constants.PROPERTY_NAME);
		if(map!=null&&map.size()>0)
			return map.get(key);
		return null;
	}
}
